package com.example.bookshop.controller;

import com.example.bookshop.service.LoginService;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @auth shanyue
 * @date 2025年06月04日16:20
 */
@Controller
@RequiredArgsConstructor
public class LoginController {
    @Resource
    private LoginService loginService;

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    @PostMapping("/register")
    public String doRegister(@RequestParam String username,
                             @RequestParam String password,
                             Model model) {
        if (loginService.isUsernameExists(username)) {
            model.addAttribute("error", "用户名已存在");
            return "register";
        }

        loginService.registerUser(username, password);
        return "redirect:/login";
    }

}
